package com.jza04.flightbooking.controller;

import com.jza04.flightbooking.entity.Flight;
import com.jza04.flightbooking.service.FlightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * 航班控制器
 */
@Controller
@RequestMapping("/flights")
public class FlightController {

    @Autowired
    private FlightService flightService;
    
    /**
     * 查询所有航班
     */
    @GetMapping
    public String listAllFlights(Model model) {
        model.addAttribute("flights", flightService.findAllFlights());
        return "flight/list";
    }
    
    /**
     * 查看航班详情
     */
    @GetMapping("/{flightId}")
    public String viewFlight(@PathVariable String flightId, Model model) {
        model.addAttribute("flight", flightService.findFlightById(flightId));
        return "flight/view";
    }
    
    /**
     * 显示添加航班表单
     */
    @GetMapping("/add")
    public String showAddForm(Model model) {
        model.addAttribute("flight", new Flight());
        return "flight/add";
    }
    
    /**
     * 处理添加航班请求
     */
    @PostMapping("/add")
    public String addFlight(Flight flight) {
        flightService.addFlight(flight);
        return "redirect:/flights";
    }
    
    /**
     * 显示编辑航班表单
     */
    @GetMapping("/edit/{flightId}")
    public String showEditForm(@PathVariable String flightId, Model model) {
        model.addAttribute("flight", flightService.findFlightById(flightId));
        return "flight/edit";
    }
    
    /**
     * 处理编辑航班请求
     */
    @PostMapping("/edit")
    public String updateFlight(Flight flight) {
        flightService.updateFlight(flight);
        return "redirect:/flights";
    }
    
    /**
     * 删除航班
     */
    @GetMapping("/delete/{flightId}")
    public String deleteFlight(@PathVariable String flightId, Model model, RedirectAttributes redirectAttributes) {
        try {
            boolean deleted = flightService.deleteFlight(flightId);
            if (deleted) {
                redirectAttributes.addFlashAttribute("successMessage", "航班删除成功");
            } else {
                redirectAttributes.addFlashAttribute("errorMessage", "航班删除失败，请稍后再试");
            }
        } catch (Exception e) {
            redirectAttributes.addFlashAttribute("errorMessage", "航班删除失败：" + e.getMessage());
        }
        return "redirect:/flights";
    }
    
    /**
     * 按路线搜索航班
     */
    @GetMapping("/search")
    public String searchFlightsByRoute(@RequestParam String departureCity, 
                                      @RequestParam String arrivalCity,
                                      Model model) {
        model.addAttribute("flights", 
                         flightService.findFlightsByRoute(departureCity, arrivalCity));
        return "flight/list";
    }
}